﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics.Contracts;

using System.ComponentModel.Composition;

namespace Kooboo.Commerce.Repositories
{
    [Export(typeof(IPaymentRepository))]
    public partial class EntityRepositories : IPaymentRepository
    {
    
        public IQueryable<IPayment> Payments
        {
            get
            {
                return this.DataReaderContext.Payments;
            }
        }

        public void Post(IPayment payment)
        {
            Contract.Requires(payment != null);

            var item = new Payment()
            {
                AmountChange = payment.AmountChange,
                HeadLine = payment.HeadLine,
                IsEnable = payment.IsEnable,
                IsRedirect = payment.IsRedirect,
                MethodName = payment.MethodName,
                PercentChange = payment.PercentChange,
                PaymentMode = (short)payment.PaymentMode
            };

            this.DataWriterContext.Payments.InsertOnSubmit(item);
            this.DataWriterContext.SubmitChanges();
        }

        public void Put(IPayment payment)
        {
            Contract.Requires(payment != null);

            var item = this.DataWriterContext.Payments
                .Where(i => i.MethodName == payment.MethodName)
                .FirstOrDefault();

            if (item == null)
            {
                throw new KeyNotFoundException("Payment: " + payment.MethodName);

            }

            item.AmountChange = payment.AmountChange;
            item.HeadLine = payment.HeadLine;
            item.IsEnable = payment.IsEnable;
            item.IsRedirect = payment.IsRedirect;
            item.MethodName = payment.MethodName;
            item.PercentChange = payment.PercentChange;
            item.PaymentMode = (short)payment.PaymentMode;

            this.DataWriterContext.SubmitChanges();
        }

        public void Delete(IPayment payment)
        {
            if (payment != null)
            {
                var item = this.DataWriterContext.Payments
                .Where(i => i.MethodName == payment.MethodName)
                .FirstOrDefault();

                if (item != null)
                {
                    this.DataWriterContext.Payments.DeleteOnSubmit(item);
                    this.DataWriterContext.SubmitChanges();
                }
            }
        }
    }
}
